package com.linh.trade.data;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class MarketData implements Runnable {

	private static final Logger LOG=LoggerFactory.getLogger(MarketData.class);
	private boolean stop;

	private boolean pause;

	private long interval;

	private List<NewPointListener> listeners;

	public MarketData() {
		listeners = new ArrayList<NewPointListener>();
	}

	protected void fireNewPointEvent(Point p) {
		p.setInView(true);
		for (NewPointListener listener : listeners) {
			listener.newPoint(p);
		}
	}

	protected void fireEndOfDataEvent() {
		for (NewPointListener listener : listeners) {
			listener.endOfData();
		}
	}

	public void addListener(NewPointListener listener) {
		listeners.add(listener);
	}

	public synchronized boolean isStop() {
		return stop;
	}

	public synchronized void setStop(boolean stop) {
		this.stop = stop;
		notify();
	}

	public synchronized boolean isPause() {
		return pause;
	}

	public synchronized void setPause(boolean pause) {
		this.pause = pause;
		notify();
	}

	public synchronized void setInterval(long interval) {
		this.interval = interval;
	}

	public void run() {
		try {
			List<Point> points = sourceData();

			for (Point p : points) {
				synchronized (this) {
					while (isPause() && !isStop()) {
						wait();
					}
					if (isStop()) {
						break;
					} else {
						fireNewPointEvent(p);
					}

				}

				try {
					Thread.sleep(interval);
				} catch (InterruptedException ie) {
				}

			}
			fireEndOfDataEvent();

		} catch (Exception ex) {
			JOptionPane.showMessageDialog(null, "Error", ex.getMessage(),
					JOptionPane.ERROR_MESSAGE);
			LOG.error("Error",ex);
		}
	}

	protected abstract List<Point> sourceData();

}
